#include "StdAfx.h"
#include "debug.h"
#include "thread.h"
#include "utility.h"

#pragma warning(disable : 4074)
#pragma init_seg(compiler)

static CJoyCriticalSection    s_logCS;

void JoySaveLogV(const char* path, const char* logText, va_list args)
{
    if(path == NULL || logText == NULL)
    {
        return;
    }

    CJoyAutoCS gate(s_logCS);

    SYSTEMTIME t;
    GetLocalTime(&t);    

	FILE* f = fopen(path, "a");
    if(f == NULL)
    {
        int i = 0;
        for( ; path[i]; ++ i)
        {
            if(path[i] == '\\' || path[i] == '/')
            {
                CString p(path, i);
                CreateDirectory(p, NULL);
            }
        }
        f = fopen(path, "a");
    }
    if(f != NULL)
    {
        fprintf(f, "[%.4d-%.2d-%.2d %.2d:%.2d:%.2d]",
            t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond);
	    vfprintf(f, logText, args);
	    fclose(f);
    }
}

void JoySaveLog(const char* path, const char* logText, ...)
{
	va_list p = va_start(p, logText);
    JoySaveLogV(path, logText, p);
}

//##ModelId=44C4B5F702A2
void CJoyLogTool::operator () (const char* logText, ...)
{
	va_list p = va_start(p, logText);
    CString path = JoyGetAppDir()+m_path;
    CString text = CString(logText)+"\n";
    JoySaveLogV(path, text, p);

}
